<?php
namespace App\Services;

use App\Model\CommissionFlow;
use App\Model\UserAccount;
use App\Model\UserAccountRecord;
use App\Model\UserPick;
use App\Model\UserPickLog;
use App\Repositories\CommissionFlowRepository;
use App\Repositories\SysConfigRepository;
use App\Repositories\UserCommissionRatioRepository;
use App\Repositories\UserCommissionStaticRepository;
use App\Repositories\UserPickRepository;
use App\Repositories\UserRelationRepository;
use App\Traits\ReturnTrait;
use Hyperf\DbConnection\Db;

class AccountService
{
    use ReturnTrait;

    public function addBalance($user_id,$money,$mask=''){
        DB::beginTransaction();
        try{
            $account = UserAccount::query()->where('user_id',$user_id)->lockForUpdate()->first();
            if(!$account){
                throw new \Exception('用户账户已删除');
            }
            $current = $account->able_balance;
            $account->balance+=$money;
            if(!$account->save()){
                throw new \Exception('账户更新失败');
            }

            $record = new UserAccountRecord();
            $record->user_id = $user_id;
            $record->type = 'balance';
            $record->amount = $money;
            $record->current = $current;
            $record->text = $mask;
            if(!$record->save()){
                throw new \Exception('账户变动日志保存失败');
            }
            DB::commit();
        }catch (\Throwable $exception){
            DB::rollBack();
            return $this->error($exception->getMessage());
        }
        return $this->success([]);
    }
}